package cn.edu.zjicm.wordsnet_d.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import android.content.Context;
import android.util.Log;
import cn.edu.zjicm.wordsnet_d.data.CustomDate;
import cn.edu.zjicm.wordsnet_d.data.StudyPlan;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference.BookType;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference.StudyMode;
import cn.edu.zjicm.wordsnet_d.db.WordFactory;

public class DateTimeUtils {

	public static java.text.DateFormat df = new java.text.SimpleDateFormat("yyyyMMdd");
	public static java.text.DateFormat df2 = new java.text.SimpleDateFormat("yyyy-MM-dd");
	public static java.text.DateFormat df3 = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public static final int MINUTES_OF_DAY = 1440; // 24*60
	public static final int SECONDS_OF_DAY = 86400; // 24*60*60
	public static final int MICROSECONDS_OF_DAY = 86400000; // 24*60*60*1000

	// public static final int STUDY_CYCLE = 15; //单词的学习周期为15天

	/* 日期和时间 */
	public static int getDate() {
		Date now = new Date();
		return Integer.parseInt(df.format(now));
	}

	/* 得到当前日期，考虑时区 */
	public static int getDateWithZoneRawOffset() {
		Date now = new Date();
		// LogUtil.e("date3",(int)
		// ((now.getTime()+TimeZone.getDefault().getRawOffset()) /
		// MICROSECONDS_OF_DAY) + "");
		return (int) ((now.getTime() + TimeZone.getDefault().getRawOffset()) / MICROSECONDS_OF_DAY);
	}

	public static int getTheDayBeforeYestorday() {
		Date now = new Date();
		now.setTime(now.getTime() -2 * 24 * 60 * 60 * 1000);
		// Log.e("thedaybeforeyestorday",df.format(now));
		return Integer.parseInt(df.format(now));
	}

	// 得到当前时间，精确到分钟(已废除，需考虑时区，改用getTimeOfMinuteWithZoneRawOffsetTime())
	public static int getTime() {
		Date now = new Date();
		return (int) (now.getTime() / 1000 / 60);
	}

	// 得到当前时间，精确到分钟，考虑时区
	public static int getTimeOfMinuteWithZoneRawOffsetTime() {
		Date now = new Date();
		return (int) ((now.getTime() + TimeZone.getDefault().getRawOffset()) / 1000 / 60);
	}

	// 得到当前时间，精确秒(已废除，需考虑时区，改用getTimeOfSecondWithZoneRawOffsetTime())
	public static int getTimeOfSecond() {
		Date now = new Date();
		return (int) (now.getTime() / 1000);
	}

	// 从yyyymmdd格式的时间转换为从1970年开始的时间
	public static int getTimeOfMinuteWithZoneRawOffsetTime(int date) {
		Date d;
		try {
			d = df.parse(date + "");
			return (int) ((d.getTime() + TimeZone.getDefault().getRawOffset()) / 1000 / 60);
		} catch (ParseException e) {
			// e.printStackTrace();
		}
		return 0;
	}

	// 将得到的从1970年开始的时间转换为yyyymmdd格式的时间
	public static int getDateFromTimeOfMinuteWithZoneRawOffsetTime(int time) {
		return Integer.parseInt(df.format(time * 1000L * 60));
	}

	// 得到当前时间，精确秒，考虑时区
	public static int getTimeOfSecondWithZoneRawOffsetTime() {
		Date now = new Date();
		return (int) ((now.getTime() + TimeZone.getDefault().getRawOffset()) / 1000);
	}

	public static String getTimeStr(long time) {
		Date d = new Date(time);
		return df3.format(d);
	}

	public static int getDaysBeforeToday(String dateStr) {
		long days = 0;
		if (dateStr.equals("0"))
			dateStr = "00000000";
		try {
			Date date = df.parse(dateStr);
			Date now = df.parse(df.format(new Date()));
			days = now.getTime() - date.getTime();
			days = days / 1000 / 60 / 60 / 24;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return (int) days;
	}

	public static int getDate2() {
		Date now = new Date();
		return Integer.parseInt(df2.format(now));
	}

	// 计算当天距离学习计划结束的时间
	public static int getPlanLastDay(Context mContext, int bookType) {
		Calendar today = Calendar.getInstance();

		int endYear = 0, endMonth = 0, endDay = 0;

		if (bookType == AppPreference.BookType.BOOK_WORD) {
			endYear = AppPreference.getWordPlanEndYear(mContext);
			endMonth = AppPreference.getWordPlanEndMonth(mContext);
			endDay = AppPreference.getWordPlanEndDay(mContext);
		} else if (bookType == AppPreference.BookType.BOOK_PHRASE) {
			endYear = AppPreference.getPhrasePlanEndYear(mContext);
			endMonth = AppPreference.getPhrasePlanEndMonth(mContext);
			endDay = AppPreference.getPhrasePlanEndDay(mContext);
		}

		Calendar endDate = Calendar.getInstance();
		endDate.set(endYear, endMonth, endDay);

		long intervalDays = (endDate.getTimeInMillis() - today.getTimeInMillis()) / MICROSECONDS_OF_DAY;
		if (intervalDays < 0) // 如果学习日期小于0，设置为0
			intervalDays = 0;
		return (int) intervalDays;
	}

	/**
	 * 主界面计算剩余时间
	 * 
	 * @param context
	 * @param bookType
	 * @return
	 */
	public static int getLeftDays(Context context, int bookType, int unlearnedCount) {
		int leftDays = 0;
		if (unlearnedCount == 0) {
			return leftDays;
		}

		if (bookType == BookType.BOOK_WORD) {
			if (AppPreference.getWordStudyMode(context) == StudyMode.MODE_END_TIME) {
				leftDays = getPlanLastDay(context, bookType);
			} else {
				int everyDayNum = AppPreference.getWordEveryDayNumber(context);
				leftDays = unlearnedCount / everyDayNum;
				if (unlearnedCount % everyDayNum > 0) {
					leftDays++;
				}
			}
		} else {
			if (AppPreference.getPhraseStudyMode(context) == StudyMode.MODE_END_TIME) {
				leftDays = getPlanLastDay(context, bookType);
			} else {
				int everyDayNum = AppPreference.getPhraseEveryDayNumber(context);
				leftDays = unlearnedCount / everyDayNum;
				if (unlearnedCount % everyDayNum > 0) {
					leftDays++;
				}
			}
		}
		return leftDays;
	}

	// 计算学习计划开始时间和学习计划结束时间的间隔天数
	public static int getPlanLastDay1(Context mContext, int bookType) {
		int planStartDay, startYear, startMonth, startDay;
		int endYear, endMonth, endDay;

		if (bookType == AppPreference.BookType.BOOK_WORD) {
			planStartDay = AppPreference.getWordPlanStartDate(mContext);
			endYear = AppPreference.getWordPlanEndYear(mContext);
			endMonth = AppPreference.getWordPlanEndMonth(mContext);
			endDay = AppPreference.getWordPlanEndDay(mContext);
		} else {
			planStartDay = AppPreference.getPhraseBookIndex(mContext);
			endYear = AppPreference.getPhrasePlanEndYear(mContext);
			endMonth = AppPreference.getPhrasePlanEndMonth(mContext);
			endDay = AppPreference.getPhrasePlanEndDay(mContext);
		}

		startYear = planStartDay / 10000;
		startMonth = planStartDay % 10000 / 100 - 1;
		startDay = planStartDay % 100;

		Calendar startDate = Calendar.getInstance();
		startDate.set(startYear, startMonth, startDay);

		Calendar endDate = Calendar.getInstance();
		endDate.set(endYear, endMonth, endDay);

		long intervalDays = (endDate.getTimeInMillis() - startDate.getTimeInMillis()) / 1000 / 60 / 60 / 24;
		if (intervalDays < 0) // 如果学习日期小于0，设置为0
			intervalDays = 0;
		return (int) intervalDays;
	}

	// 计算参数中的日期距离参数中确定的学习计划结束的时间
	public static int getPlanLastDay(Context mContext, int endYear, int endMonth, int endDay) {
		Calendar today = Calendar.getInstance();
		Calendar endDate = Calendar.getInstance();
		endDate.set(endYear, endMonth, endDay);
		long intervalDays = (endDate.getTimeInMillis() - today.getTimeInMillis()) / 1000 / 60 / 60 / 24;
		// Toast.makeText(this,
		// endYear + "_" + endMonth + "_" + endDay + " " + intervalDays,
		// Toast.LENGTH_SHORT).show();
		return (int) intervalDays;
	}

	// 根据当天距离学习计划结束的时间和单词书中未学单词的个数，计算每天应推送的生词的个数
	public static int getWordsNumPerDayForPlan(Context mContext, StudyPlan studyPlan, boolean fromStartDate) {
		int unlearnedWordNum = WordFactory.getInstance(mContext).getUnLearnedWordCount(studyPlan.getBookIndex());
		int planDays;
		if (fromStartDate) {
			planDays = DateTimeUtils.getPlanLastDay1(mContext, studyPlan.getBookType());
		} else {
			planDays = DateTimeUtils.getPlanLastDay(mContext, studyPlan.getBookType());
		}
		int wordsNumPerDay;
		if (planDays <= 0) {
			wordsNumPerDay = unlearnedWordNum;
		} else {
			wordsNumPerDay = unlearnedWordNum / planDays;
			if (unlearnedWordNum % planDays > 0)
				wordsNumPerDay++;
		}
		return wordsNumPerDay;
	}

	// 根据学习计划结束的时间和学习计划开始时间，计算每天应推送的生词的个数 注释 by ct v2.11.0
	// public static int getWordsNumPerDayForPlan1(Context mContext) {
	// int wordAllNum = 0, phraseAllNum = 0;
	// if (AppPreference.getWordBookIndex(mContext) != -1 &&
	// AppPreference.getWordBookIsLearning(mContext)) {
	// wordAllNum =
	// WordFactory.getInstance(mContext).getWordCountInBook(AppPreference.getWordBookIndex(mContext));
	// }
	// if (AppPreference.getPhraseBookIndex(mContext) != -1 &&
	// AppPreference.getPhraseBookIsLearning(mContext)) {
	// phraseAllNum =
	// WordFactory.getInstance(mContext).getWordCountInBook(AppPreference.getPhraseBookIndex(mContext));
	// }
	// int planDays = DateTimeUtils.getPlanLastDay1(mContext);
	// int wordsNumPerDay;
	// if (planDays <= 0) {
	// wordsNumPerDay = allWordNum;
	// } else {
	// wordsNumPerDay = allWordNum / planDays;
	// if (allWordNum % planDays > 0)
	// wordsNumPerDay++;
	// }
	// Log.e("allWordNum", allWordNum + "");
	// Log.e("planDays", planDays + "");
	// Log.e("wordsNumPerDay", wordsNumPerDay + "");
	// return wordsNumPerDay;
	// }

	// 根据当天距离学习计划结束的时间和单词书中未学单词的个数，计算每天应推送的生词的个数
	public static int getWordsNumPerDayForPlan(Context mContext, int bookIndex, int endYear, int endMonth, int endDay) {
		int unlearnedWordNum = WordFactory.getInstance(mContext).getUnLearnedWordCount(bookIndex);
		int planDays = DateTimeUtils.getPlanLastDay(mContext, endYear, endMonth, endDay);

		int wordsNumPerDay;
		if (planDays <= 0) {
			wordsNumPerDay = unlearnedWordNum;
		} else {
			wordsNumPerDay = unlearnedWordNum / planDays;
			if (unlearnedWordNum % planDays > 0)
				wordsNumPerDay++;
		}
		Log.e("unlearnedWordNum", unlearnedWordNum + "");
		Log.e("planDays", planDays + "");
		Log.e("wordsNumPerDay", wordsNumPerDay + "");
		return wordsNumPerDay;
	}

	// 将单词书中单词个数传入，减少查询数据库
	public static int getWordsNumberPerDayForPlan2(int unlearnedWordNum, Context mContext, int endYear, int endMonth, int endDay) {
		int planDays = DateTimeUtils.getPlanLastDay(mContext, endYear, endMonth, endDay);

		LogUtil.d("endYear=" + endYear + ",endMonth=" + endMonth + ",endDay=" + endDay + ",planDays=" + planDays);

		int wordsNumPerDay;
		if (planDays <= 0) {
			wordsNumPerDay = unlearnedWordNum;
		} else {
			wordsNumPerDay = unlearnedWordNum / planDays;
			if (unlearnedWordNum % planDays > 0)
				wordsNumPerDay++;
		}
		Log.e("unlearnedWordNum", unlearnedWordNum + "");
		Log.e("planDays", planDays + "");
		Log.e("wordsNumPerDay", wordsNumPerDay + "");
		return wordsNumPerDay;
	}

	// 每天学习600个单词，至少需要的天数
	public static int getSuitableDays(Context mContext, int bookID) {
		int unlearnedWordNum = WordFactory.getInstance(mContext).getUnLearnedWordCount(bookID);
		int days = unlearnedWordNum / 600;
		if (unlearnedWordNum / 600 > 0)
			days++;
		return days;
	}

	// 得到学习计划结束时间
	// public static String getPlanEndDate(Context mContext) {
	// int year = AppPreference.getPlanEndYear(mContext);
	// int month = AppPreference.getPlanEndMonth(mContext);
	// int day = AppPreference.getPlanEndDay(mContext);
	//
	// int daysOfMonth = DateTimeUtils.getDaysOfMonth(year, month + 1);
	// if (day > daysOfMonth) {
	// day = daysOfMonth;
	// AppPreference.setPlanEndDay(mContext, day);
	// }
	//
	// /*
	// * Date endDate = new Date(); endDate.setYear(year - 1900);
	// * endDate.setMonth(month); endDate.setDate(day);
	// *
	// * return df2.format(endDate);
	// */
	// month = month + 1;
	// String str = year + "-";
	// if (month < 10)
	// str = str + "0";
	// str = str + month;
	// str = str + "-";
	// if (day < 10)
	// str = str + "0";
	// str = str + day;
	// return str;
	// }

	// 根据每天学习个数计算需要学习多少天
	public static int getDaysByStudyNumPerDay(int unlearnedWordNum, int studyNumPerDay) {
		if (unlearnedWordNum == 0 || studyNumPerDay == 0) {
			return 0;
		}
		int mol = unlearnedWordNum % studyNumPerDay;
		int days = unlearnedWordNum / studyNumPerDay;
		if (mol > 0)
			days++;
		return days;
	}

	// 计算某年某月天数
	public static int getDaysOfMonth(int year, int month) {
		int daysOfMonth[][] = { { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } };

		if (isLeapYear(year))
			return daysOfMonth[1][month];
		else
			return daysOfMonth[0][month];
	}

	public static boolean isLeapYear(int year) {
		return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
	}

	public static String[] weekName = { "周日", "周一", "周二", "周三", "周四", "周五", "周六" };

	public static int getYear() {
		return Calendar.getInstance().get(Calendar.YEAR);
	}

	public static int getMonth() {
		return Calendar.getInstance().get(Calendar.MONTH) + 1;
	}

	public static int getCurrentMonthDay() {
		return Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
	}

	public static int getWeekDay() {
		return Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
	}

	public static int getMonthDays(int year, int month) {
		if (month > 12) {
			month = 1;
			year += 1;
		} else if (month < 1) {
			month = 12;
			year -= 1;
		}
		int[] arr = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
		int days = 0;

		if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
			arr[1] = 29; // 闰年2月29天
		}

		try {
			days = arr[month - 1];
		} catch (Exception e) {
			e.getStackTrace();
		}

		return days;
	}

	/**
	 * 判断指定月的1号是星期几
	 * 
	 * @param year
	 * @param month
	 * @return
	 */
	public static int getWeekDayFromDate(int year, int month) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(getDateFromString(year, month));
		int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (week_index < 0) {
			week_index = 0;
		}
		return week_index;
	}

	public static Date getDateFromString(int year, int month) {
		String dateString = year + "-" + (month > 9 ? month : ("0" + month)) + "-01";
		Date date = null;
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			date = sdf.parse(dateString);
		} catch (ParseException e) {
			System.out.println(e.getMessage());
		}
		return date;
	}

	public static boolean isCurrentMonth(CustomDate date) {
		return (date.year == DateTimeUtils.getYear() && date.month == DateTimeUtils.getMonth());
	}

	public static int getTodayMonthIndex(Calendar today) {
		int offset = (today.get(Calendar.YEAR) - getMinYear()) * 12 + today.get(Calendar.MONTH);
		return offset;
	}

	private static final int YEAR_MAX = 2040;
	private static final int YEAR_MIN = 1990;

	public static int getMinYear() {
		return YEAR_MIN + 1;
	}

	public static int getMaxYear() {
		return YEAR_MAX;
	}

	public static String getEnglishMonth(int month) {
		String[] engMonth = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
		return engMonth[month - 1];
	}

	public static String getSecondTime() {
		Date d = new Date();
		return df3.format(d);
	}

	/**
	 * 获取单词的学习计划中每天需学习个数 v2.11.0 add by ct
	 * 
	 * @param fromStartDate
	 *            是否从开始时间计算
	 * @return
	 */
	public static int getWordBookNumPerDayForPlan(Context context, boolean fromStartDate) {
		int wordNum = 0;
		StudyPlan wordStudyPlan = StudyPlan.getWordStudyPlan(context);

		if (wordStudyPlan != null && wordStudyPlan.isLearning()) {
			if (wordStudyPlan.getStudyMode() == AppPreference.StudyMode.MODE_END_TIME) {
				wordNum += DateTimeUtils.getWordsNumPerDayForPlan(context, wordStudyPlan, fromStartDate);
			} else {
				int everyDayCount = wordStudyPlan.getEveryDayNumber(); // 每天学习个数
				int unlearnedWordCount = WordFactory.getInstance(context).getUnLearnedWordCount(wordStudyPlan.getBookIndex());
				if (unlearnedWordCount < everyDayCount) // 如果该单词书中的未学单词小于每天学习个数，则推送剩下所有的未学单词
					everyDayCount = unlearnedWordCount;
				wordNum += everyDayCount;
			}
		}
		return wordNum;
	}

	/**
	 * 获取词组的学习计划中每天需学习的单词个数 v2.11.0 add by ct
	 * 
	 * @param fromStartDate
	 *            是否从开始时间计算
	 * @param context
	 * @return
	 */
	public static int getPhraseBookNumPerDayForPlan(Context context, boolean fromStartDate) {
		int phraseNum = 0;
		StudyPlan phraseStudyPlan = StudyPlan.getPhraseStudyPlan(context);

		if (phraseStudyPlan != null && phraseStudyPlan.isLearning()) {
			if (phraseStudyPlan.getStudyMode() == AppPreference.StudyMode.MODE_END_TIME) {
				phraseNum += DateTimeUtils.getWordsNumPerDayForPlan(context, phraseStudyPlan, fromStartDate);
			} else {
				int everyDayCount = phraseStudyPlan.getEveryDayNumber(); // 每天学习个数
				int unlearnedPhraseCount = WordFactory.getInstance(context).getUnLearnedWordCount(phraseStudyPlan.getBookIndex());
				if (unlearnedPhraseCount < everyDayCount)
					everyDayCount = unlearnedPhraseCount;
				phraseNum += everyDayCount;
			}
		}

		return phraseNum;
	}

	public static Calendar getEndTimeByEveryDayNum(int unlearnedCount, int everyDayNumber) {
		int needStudyDays = DateTimeUtils.getDaysByStudyNumPerDay(unlearnedCount, everyDayNumber);
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DAY_OF_YEAR, needStudyDays);
		return calendar;
	}
}
